package com.example.springbootjwtexample.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootjwtexample.koal.ByteUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;

public class JWTParseUtil {

    public static Pair<JSONObject, JSONObject> jwtParser(String jwtString){
        Pair<JSONObject,JSONObject> pair = new MutablePair<>();
        if (StringUtils.isNotBlank(jwtString)) {
            String[] splitStrings = jwtString.split("\\.");
            if (splitStrings.length < 3) {
                throw new IllegalArgumentException("参数错误");
            }
            String headerCipher = splitStrings[0];
            byte[] headerBytes = ByteUtil.base64UrlDecode(headerCipher);
            JSONObject headerJSON = JSONObject.parseObject(headerBytes,JSONObject.class);

            String payloadCipher = splitStrings[1];
            byte[] payloadBytes = ByteUtil.base64UrlDecode(payloadCipher);
            JSONObject payloadJSON = JSONObject.parseObject(payloadBytes,JSONObject.class);
            pair = MutablePair.of(headerJSON,payloadJSON);
            return pair;
        }
        return pair;
    }
}
